package com.ablife.limiter.controller;

import com.alibaba.fastjson.JSON;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Controller
public class WebController {
    private static final Logger logger = LoggerFactory.getLogger(WebController.class);
    @Autowired
    JedisPool jedisPool;

    public WebController() {
    }

    @RequestMapping({"/config"})
    public String config() {
        logger.info("------access_into_config_page------");
        return "config";
    }

    /**
     * @author hzh
     * description: 取出所有keys
     */
    @RequestMapping(
            value = {"/initConfig"},
            produces = {"text/html;charset=UTF-8;"}
    )
    @ResponseBody
    public String initConfig() throws UnsupportedEncodingException {
        Jedis jedis = this.jedisPool.getResource();
        Set<byte[]> keySet = jedis.keys("*".getBytes("UTF-8"));
        byte[][] keys = (byte[][])keySet.toArray(new byte[keySet.size()][]);
        byte[][] values = (byte[][])jedis.mget(keys).toArray(new byte[keySet.size()][]);
        Map map = new HashMap();

        for(int i = 0; i < keySet.size(); ++i) {
            map.put(new String(keys[i], "UTF-8"), new String(values[i], "utf-8"));
        }

        jedis.close();
        return JSON.toJSONString(map);
    }

    /**
     * @author hzh
     * description: 更新开关状态
     * @param switchValue 是否开启：0关闭，1开启
     */
    @RequestMapping({"/updateSwitch"})
    @ResponseBody
    public void updateSwitch(String switchValue) {
        Jedis jedis = this.jedisPool.getResource();
        jedis.set("MAINSWITCH", switchValue);
        jedis.close();
        logger.info("-----update_main_switch(0:close，1:open)---current_value:" + switchValue);
    }

    @RequestMapping({"/deleteKey"})
    @ResponseBody
    public void deleteKey(String key) {
        key = key.toUpperCase();
        Jedis jedis = this.jedisPool.getResource();
        jedis.del(key);
        if (key.indexOf("CONFIG") == 0) {
            jedis.del("TRADECOUNT|" + key.substring(7));
        }

        if (key.indexOf("TRADECONFIG") == 0) {
            String[] strs = key.split("\\|");
            jedis.del(strs[2] + "|" + strs[1] + "|" + "SUCCESS");
            jedis.del(strs[2] + "|" + strs[1] + "|" + "FAILURE");
        }

        jedis.close();
        logger.info("--------delete_config_key=------------" + key);
    }

    @RequestMapping({"/updateKeys"})
    @ResponseBody
    public void updateKeys(String[] keys, String[] values) throws UnsupportedEncodingException {
        Jedis jedis = this.jedisPool.getResource();

        for(int i = 0; i < keys.length; ++i) {
            String key = keys[i].toUpperCase();
            String value = values[i];
            String oldValue = jedis.get(key);
            jedis.set(key, value);
            if (!StringUtils.isEmpty(oldValue)) {
                logger.info("-----update_config--" + key + "----old_value:" + oldValue + "----new_value:" + value + "-------");
            } else {
                logger.info("--------add_config------key:" + key + "--value:" + value + "-------");
            }
        }

        jedis.close();
    }
}
